import React, {Component} from "react";
import http from "../../../utils/Api";
import {Table, Button, Input, Modal, Form, Select} from "antd";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import "./index.css";
import axios from "axios";
const {Option} = Select;


class BarryList extends Component {
    form = React.createRef()
    state = {
        barryList: [],
        columns: [
            {title: "编号", dataIndex: "id", key: "id"},
            {
                title: "租金(每分钟/$)",
                dataIndex: "rent",
                key: "id",
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "id",
                render: (status,item) => <Button
                    type={item.status === 1 ? 'primary' : 'danger'} onClick={() => this.showUpdateConfirm(status,item)}>{item.status === 1 ? '正常' : '禁用'}</Button>
            },
            {
                title: '设备名字',
                dataIndex: "name",
                key: "id",
                render: (name,item) => <div>{item.froEquipment.name}</div>
            },
            {
              title: '备注',
              dataIndex: 'remark',
              render: (remark) => <span>{remark}</span>
            },
            {
                title: "操作",
                dataIndex: "id",
                /* 高阶函数，此处的id是dataIndex的id */
                render: (id) => <Button danger onClick={() => this.showDeleteConfirm(id)}>删除</Button>
            }
        ],
        params: {
            pageSize: '10',
            currentPage: '1',
            status: '',
            equipmentName: ''
        },
        equipmentList: [],
        froBattery: {
            id: 0,
            rent: '',
            status: '',
            equipmentId: '',
            remark: ''
        },
        /* 分页 */
        pagination: {
            total: 0,
            currentPage: 1
        },
        isModalVisible: false
    };

    // 获取充电宝列表
    getBarryList = () => {
        const { params } = this.state
        http.getRequest("/fro/battery/list", params).then(({data})=> {
            console.log(data);
            this.setState({
                barryList: data.data,
                pagination: {
                    ...this.state.pagination,
                    total: data.total
                }
            });
        })
    }

    // 获取设备
    getEquipment=()=> {
        http.getRequest('/sys/equipment/list').then(({data}) => {
            this.setState({
                equipmentList: data.data
            })
        })
    }

    /* 状态更改的弹窗 */
    showUpdateConfirm = (statusCol,item) => {
        Modal.confirm({
            title: "你确定要修改吗?",
            icon: <ExclamationCircleOutlined/>,
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            onOk: () => {
                const status = statusCol === 1 ? 2 : 1
                this.UpdateDisabled(status,item)
            }
        });
    }

    /* 状态更改方法 */
    UpdateDisabled = (status,item) => {
        const {id} = item
        const query = {
            id,
            status
        }
        http.postRequest_form('/fro/battery/status', query).then(({data}) => {
            console.log('@',data);
            if (data.code === 200) {
                this.getBarryList()
            }
        })
    }

    /* 删除按钮，点击弹出 */
    showDeleteConfirm = (id) => {
        Modal.confirm({
            title: "你确定要删除吗?",
            icon: <ExclamationCircleOutlined/>,
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            onOk: () => {
                this.deleteBarry(id)
            }
        });
    };

    /* 删除按钮的方法，被onOk调用 */
    deleteBarry = (id) => {
        http.deleteRequest(`/fro/battery/delete/${id}`).then(({data}) => {
            if (data.code===200) {
                console.log(data);
                this.getBarryList()
            }
        })
        console.log(id);
    }

    /* 确认添加 */
    addBarry = (values) => {
        this.setState({
            froBattery: {...values}
        },() => {
            axios.post('/fro/battery/edit', this.state.froBattery).then(({data}) => {
                if (data.code === 200) {
                    this.getBarryList()
                }
            })
            this.setState(state => ({isModalVisible: false}));
        })
    };

    /* 取消添加 */
    handleCancel = () => {
        this.setState(state => ({isModalVisible: false}));
    };

    /* 切换状态 */
    handleChange = (value) => {
        console.log(value);
    };

    /*更改一页显示条数*/
    changePage=(page,pageSize)=>{
        console.log(page,pageSize)
        this.setState({
            params:{
                ...this.state.params,
                pageSize:pageSize,
                currentPage:page
            },
            pagination: {
                ...this.state.pagination,
                currentPage: page
            },
            batteryInfo: {
                id: 0
            }
        },()=>{
            this.getBarryList()
        })

    }
    componentDidMount() {
        console.log(this.props);
        this.getBarryList();
    }

    render() {
        return (
            <div>
                <Form layout={"inline"} style={{marginBottom: '30px'}}>
                    <Form.Item>
                        <Input placeholder="请输入设备名" name={'name'} onChange={(e) => {
                            console.log(e.target.name);
                            this.setState({
                                params: {
                                    ...this.state.params,
                                    equipmentName: e.target.value
                                }
                            })
                        }} />
                    </Form.Item>
                    <Form.Item>
                        <Select defaultValue={0} style={{ width: 100 }} onChange={(e) => {
                            console.log(e);
                            this.setState({
                            params: {
                                ...this.state.params,
                                status: e
                            }
                        })}}>
                            <Option value={0}>所有状态</Option>
                            <Option value={1}>可用状态</Option>
                            <Option value={2}>禁用状态</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={()=> {this.getBarryList()}}>查询</Button>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={() => {
                            this.setState({
                                isModalVisible: true
                            });
                            this.getEquipment();
                        }} >添加充电宝</Button>
                    </Form.Item>
                        <Modal
                            visible={this.state.isModalVisible}
                            title={this.state.froBattery.id === 0 ? '添加充电宝' : '删除充电宝'}
                            okText="添加"
                            cancelText="取消"
                            onCancel={this.handleCancel}
                            onOk={() => {
                                console.log(this.form);
                                this.form.current
                                    .validateFields()
                                    .then((values) => {
                                        this.form.current.resetFields();
                                        this.addBarry(values);
                                    })
                                    .catch((info) => {
                                        console.log('Validate Failed:', info);
                                    });
                            }}
                        >
                            <Form
                                ref={this.form}
                                layout="vertical"
                                name="form_in_modal"
                                initialValues={{
                                    modifier: "public"
                                }}
                            >
                                <Form.Item
                                    name="rent"
                                    label="充电宝租金"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请输入充电宝租金"
                                        }
                                    ]}
                                >
                                    <Input/>
                                </Form.Item>
                                <Form.Item
                                    name="status"
                                    label="充电宝状态"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请选择充电宝状态"
                                        }
                                    ]}
                                >
                                    <Select style={{width: 120}} onChange={this.handleChange}>
                                        <Option value="1">正常</Option>
                                        <Option value="2">禁用</Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item
                                    name="equipmentId"
                                    label="设备Id"
                                    rules={[
                                        {
                                            required: true,
                                            message: "请选择设备id"
                                        }
                                    ]}
                                >
                                    <Select style={{width: 120}} onChange={this.handleChange}>
                                        {
                                            this.state.equipmentList.map(item=> {
                                                return <option value={item.id}>{item.name}</option>
                                            })
                                        }
                                    </Select>
                                </Form.Item>
                                <Form.Item
                                    name="remark"
                                    label="充电宝备注"
                                    rules={[
                                        {
                                            required: false
                                        }
                                    ]}
                                >
                                    <Input/>
                                </Form.Item>
                            </Form>
                        </Modal>
                </Form>
                <Table dataSource={this.state.barryList} pagination={{pageSize: 100}} scroll={{y: 450}}
                       columns={this.state.columns}>
                </Table>
            </div>
        );
    }
}

export default BarryList;
